package com.song.osclient.update;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.view.WindowManager;


import com.loopj.android.http.TextHttpResponseHandler;
import com.song.osclient.R;
import com.song.osclient.http.Http;
import com.song.osclient.view.PrintToast;
import com.song.osclient.dialog.DialogHelper;
import com.song.osclient.util.PrintLog;

import org.apache.http.Header;


public class UpdateService extends Service {
    private boolean isShow;
    private ProgressDialog loading;

    public void checkUpdate() {
        Http.getHttpClient().post(this, Http.getAbsoluteUrl("/apk/version.txt"), null, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                if (isShow) {
                    showCheckDialog();
                }
            }

            @Override
            public void onFinish() {
                if (isShow) {
                    hideCheckDialog();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                if (isShow) {
                    showFailDialog();
                }
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                int versionCode = 2;//todo change to real
                onFinishCheck(new UpdateInfo(versionCode, "1.1", "1.添加了XX功能\n2.修复BUG", "http://211.138.17.55:20003/down/apk/10085nfc.apk"));
            }
        });
    }

    private void onFinishCheck(UpdateInfo updateInfo) {
        if (updateInfo.isHasNewVersion()) {
            showUpdateInfo(updateInfo);
        } else {
            if (isShow) showLatestDialog();
        }
    }

    private void showCheckDialog() {
        if (loading == null) {
            loading = DialogHelper.getLoadingDialog(this, "正在获取新版本信息...");
        }
        loading.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
        loading.show();
    }

    private void hideCheckDialog() {
        if (loading != null && loading.isShowing()) {
            loading.dismiss();
        }
    }

    private void showUpdateInfo(final UpdateInfo info) {
        AlertDialog.Builder builder = DialogHelper.getConfirmDialog(this, info.getUpdateLog(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                startDownLoadService(UpdateService.this, info.getDownloadUrl(), " " + getString(R.string.app_name));
            }
        });
        builder.setTitle("发现新版本：" + info.getVersionName());
        AlertDialog dialog = builder.create();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();
    }

    private void showLatestDialog() {
        PrintToast.print("已经是新版本了");
    }

    private void showFailDialog() {
        DialogHelper.getConfirmDialog(this, "网络异常，无法获取新版本信息").show();
    }

    private void startDownLoadService(Context context, String downUrl, String title) {
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra(DownloadService.BUNDLE_KEY_DOWNLOAD_URL, downUrl);
        intent.putExtra(DownloadService.BUNDLE_KEY_TITLE, title);
        context.startService(intent);
    }

    @Override
    public void onDestroy() {
        PrintLog.error("update service error");
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            isShow = intent.getBooleanExtra("isShow", false);
            checkUpdate();
        }
        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
